<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
import { useUserStore } from "@/store/modules/user";
import UserProfile from "./components/UserProfile.vue";
import MenuTabs from "./components/MenuTabs.vue";
import MyVideosView from "./views/MyVideosView.vue";
import FavoritesView from "./views/FavoritesView.vue";
import HistoryView from "./views/HistoryView.vue";
import ConcernView from "./views/ConcernView.vue";
import FansView from "./views/FansView.vue";
import { getUserInfoById } from "@/api/user"; // 假设有这些API
import { followUserApi, unfollowUserApi } from "@/api/follow"; 
// 获取用户数据
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();

// 定义props来接收路由参数
const props = defineProps({
  userId: { type: String, default: "" },
});

// 是否为查看他人中心
const isViewingOtherUser = computed(() => !!props.userId);

// 是否已关注该用户
const isFollowing = ref(false);

// 烟花效果相关变量
const showFireworks = ref(false);
const fireworksCount = ref(6);

// 当前用户数据与正在查看的用户数据
const currentUserInfo = computed(() => ({
  id: userStore.userInfo.id || "",
  username: userStore.userInfo.username || "未设置昵称",
  avatar:
    userStore.userInfo.avatar ||
    "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
  email: userStore.userInfo.email || "",
  follows: userStore.userInfo.following_count || 0,
  fans: userStore.userInfo.follower_count || 0,
  bio: userStore.userInfo.bio || "这个人很懒，还没有填写个人简介",
}));

// 查看的用户信息（可能是自己，也可能是他人）
const userInfo = ref({ ...currentUserInfo.value });

// 关注/取消关注用户
async function toggleFollow() {
  try {
    if (isFollowing.value) {
      await unfollowUserApi(props.userId);
      isFollowing.value = false;
      ElMessage.success("已取消关注");
    } else {
      await followUserApi(props.userId);
      isFollowing.value = true;
      ElMessage.success("关注成功");
    }
    // 更新用户信息
    await fetchUserData();
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  }
}

// 根据不同模式显示不同的菜单选项
const menuItems = computed(() => {
  if (isViewingOtherUser.value) {
    // 查看他人中心时，只显示视频和粉丝关注
    return [
      { id: "myVideos", name: "Ta的视频", icon: "icon-video" },
    ];
  } else {
    // 查看自己的中心时，显示完整菜单
    return [
      { id: "myVideos", name: "我的视频", icon: "icon-video" },
      { id: "favorites", name: "我的收藏", icon: "icon-star" },
      { id: "history", name: "观看历史", icon: "icon-history" },
      { id: "concern", name: "关注", icon: "icon-concern" },
      { id: "fans", name: "粉丝", icon: "icon-fans" },
      { id: "settings", name: "设置", icon: "icon-settings" },
    ];
  }
});

// 当前选中的菜单项
const activeMenu = ref("myVideos");

// 切换菜单
function switchMenu(menuId) {
  activeMenu.value = menuId;
}

// 获取指定用户的数据
async function fetchUserData() {
  if (isViewingOtherUser.value) {
    try {
      // 调用API获取其他用户信息
      const userData = await getUserInfoById(props.userId);
      // 检查当前用户是否已关注此用户
      isFollowing.value = userData.isFollowing || false;

      // 更新用户信息
      userInfo.value = {
        id: userData.id,
        username: userData.username || "未设置昵称",
        avatar:
          userData.avatar ||
          "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
        email: userData.email || "",
        follows: userData.following_count || 0,
        fans: userData.follower_count || 0,
        bio: userData.bio || "这个人很懒，还没有填写个人简介",
      };
    } catch (error) {
      console.error("获取用户信息失败:", error);
      ElMessage.error("获取用户信息失败，请稍后重试");
    }
  } else {
    // 查看自己的资料，使用store中的数据
    userInfo.value = { ...currentUserInfo.value };
  }
}

// 编辑个人信息
async function updateProfile(updatedInfo) {
  try {
    // 调用更新用户信息接口
    await userStore.updateUserInfo(updatedInfo);

    // 重新获取用户信息确保数据一致性
    await userStore.fetchUserInfo();
    // 更新当前显示的用户信息
    userInfo.value = { ...currentUserInfo.value };
  } catch (error) {
    console.error("更新个人信息失败:", error);
    ElMessage.error("更新个人信息失败，请稍后重试");
  }
}

// 处理退出登录
function handleLogout() {
  ElMessageBox.confirm("确定要退出登录吗?", "退出登录", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await userStore.logout();
      // 退出成功后跳转到首页
      router.push("/");
    })
    .catch(() => {
      // 用户取消操作
    });
}

// 监听userId的变化，重新获取用户数据
watch(
  () => props.userId,
  () => {
    fetchUserData();
    activeMenu.value = "myVideos"; // 重置为默认标签
  }
);

// 组件挂载时获取用户数据
onMounted(async () => {
  // 检查用户是否登录
  if (userStore.isLoggedIn()) {
    await userStore.fetchUserInfo();
  }

  // 获取当前要显示的用户数据
  fetchUserData();
});
</script>

<template>
  <div class="mine-container">
    <!-- 用户信息展示区 -->
    <UserProfile
      :userInfo="userInfo"
      :isViewingOtherUser="isViewingOtherUser"
      :isFollowing="isFollowing"
      @update-profile="updateProfile"
      @toggle-follow="toggleFollow"
    />

    <!-- 菜单区域 -->
    <div class="menu-section">
      <!-- 菜单选项 -->
      <MenuTabs
        :menuItems="menuItems"
        :activeMenu="activeMenu"
        @switch-menu="switchMenu"
      />
      <!-- 内容展示区 -->
      <!-- 内容展示区 -->
      <div class="content-section">
        <MyVideosView
          v-if="activeMenu === 'myVideos'"
          :userId="isViewingOtherUser ? userId : ''"
        />

        <FavoritesView v-else-if="activeMenu === 'favorites'" />

        <HistoryView v-else-if="activeMenu === 'history'" />

        <ConcernView
          v-else-if="activeMenu === 'concern'"
        />

        <FansView
          v-else-if="activeMenu === 'fans'"
        />

        <div v-else-if="activeMenu === 'settings'" class="content-panel">
          <h3>设置</h3>
          <div class="settings-list">
            <div class="settings-item" @click="handleLogout">
              <span class="settings-icon">👤</span>
              <span>退出登录</span>
            </div>
            <div class="settings-item" @click="showAboutWebsite">
              <span class="settings-icon">ℹ️</span>
              <span>关于网站</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="showFireworks" class="improved-fireworks-container">
      <div
        v-for="i in fireworksCount"
        :key="i"
        class="firework-launcher"
        :style="{
          '--left': getRandomInt(20, 80) + '%',
          '--launchDelay': getRandomInt(0, 1500) + 'ms',
        }"
      >
        <div class="launcher-body"></div>

        <!-- 每个烟花粒子创建20个粒子 -->
        <div
          v-for="j in 20"
          :key="j"
          class="firework-particle"
          :style="getRandomParticleStyle(j, 20)"
        ></div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.mine-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  background-color: #161823;
  padding: 16px;
  gap: 16px;
}

/* 菜单区域样式 */
.menu-section {
  background-color: #272933;
  flex: 1;
  display: flex;
  flex-direction: column;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);

  /* 内容展示区样式 */
  .content-section {
    flex: 1;
    min-height: 0;
    padding: 8px;
    overflow-y: auto;
    color: #ffffff;

    /* 隐藏滚动条但保持滚动功能 */
    /* Webkit浏览器（Chrome、Safari、新版Edge） */
    &::-webkit-scrollbar {
      width: 0;
      display: none;
    }

    /* Firefox */
    scrollbar-width: none;

    /* IE 和旧版 Edge */
    -ms-overflow-style: none;
  }
}

.content-panel {
  display: flex;
  flex-direction: column;
  height: 100%;

  /* 占满父容器高度 */
  h3 {
    margin-top: 8px;
    margin-bottom: 16px;
    font-weight: 500;
    font-size: 1.4rem;
    color: #ffffff;
    border-left: 4px solid #0096ff;
    padding-left: 12px;
  }
}

.empty-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #99a3a7;
  border-radius: 12px;
  background-color: #1f2129;
  padding: 32px;

  .empty-icon {
    font-size: 3rem;
    margin-bottom: 16px;
  }

  .empty-text {
    font-size: 1.1rem;
    margin-bottom: 24px;
  }

  .upload-button {
    padding: 10px 24px;
    background: linear-gradient(45deg, #0096ff, #6c47ff);
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 0.95rem;
    transition: all 0.2s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 150, 255, 0.3);
    }
  }
}

.settings-list {
  background-color: #1f2129;
  border-radius: 12px;
  overflow: hidden;

  .settings-item {
    padding: 16px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 12px;

    &:hover {
      background-color: rgba(0, 150, 255, 0.1);
      padding-left: 20px;
    }

    &:last-child {
      border-bottom: none;
    }

    .settings-icon {
      font-size: 1.2rem;
    }
  }
}

.favorites-container {
  display: flex;
  gap: 24px;
  flex: 1;
  overflow: hidden;

  /* 防止内容溢出 */
  .favorites-sidebar {
    width: 240px;
    background-color: #1f2129;
    border-radius: 12px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .sidebar-header {
      padding: 16px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      display: flex;
      justify-content: space-between;
      align-items: center;

      h4 {
        margin: 0;
        font-size: 1rem;
        font-weight: 500;
      }

      .add-folder-btn {
        background: transparent;
        color: #0096ff;
        border: 1px solid #0096ff;
        border-radius: 4px;
        padding: 4px 8px;
        font-size: 0.8rem;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 4px;
        transition: all 0.2s ease;

        &:hover {
          background-color: rgba(0, 150, 255, 0.1);
        }
      }
    }

    .folder-list {
      flex: 1;
      overflow-y: auto;
      padding: 8px;

      .folder-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          background-color: rgba(255, 255, 255, 0.05);
        }

        &.active {
          background-color: rgba(0, 150, 255, 0.15);

          .folder-name {
            color: #0096ff;
          }
        }

        .folder-icon {
          font-size: 1.3rem;
        }

        .folder-info {
          flex: 1;
          overflow: hidden;

          .folder-name {
            font-size: 0.95rem;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .folder-count {
            font-size: 0.8rem;
            color: #99a3a7;
          }
        }
      }
    }
  }
}

.favorites-content {
  flex: 1;
  background-color: #1f2129;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .folder-header {
    padding: 16px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;

    h4 {
      margin: 0;
      font-size: 1.1rem;
      font-weight: 500;
    }

    .folder-actions {
      display: flex;
      gap: 8px;
    }

    .folder-action-btn {
      background: transparent;
      border: 1px solid rgba(255, 255, 255, 0.2);
      color: #ffffff;
      border-radius: 4px;
      padding: 6px 10px;
      font-size: 0.8rem;
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 4px;
      transition: all 0.2s ease;

      &:hover {
        background-color: rgba(255, 255, 255, 0.05);
      }

      &.delete:hover {
        background-color: rgba(255, 73, 73, 0.2);
        border-color: rgba(255, 73, 73, 0.5);
        color: #ff4949;
      }
    }
  }

  .favorites-video-list {
    padding: 16px;
    overflow-y: auto;
    flex: 1;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    /* 关键修改：添加固定的行高 */
    grid-auto-rows: 320px;
    gap: 20px;
    align-content: start;
    height: 100%;
    min-height: 0;

    .favorite-video-card {
      background-color: #1f2129;
      border-radius: 12px;
      overflow: hidden;
      transition: transform 0.2s ease, box-shadow 0.2s ease;
      cursor: pointer;
      position: relative;
      display: flex;
      flex-direction: column;
      /* 移除min-height属性，改为使用grid-auto-rows控制高度 */
      height: 100%;

      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);

        .video-cover {
          transform: scale(1.05);
        }

        .remove-button {
          opacity: 1;
        }
      }

      .video-cover-container {
        position: relative;
        width: 100%;
        /* 将flex属性添加到封面容器，让其占据固定比例 */
        flex: 0 0 auto;
        height: 65%;
        /* 封面占卡片总高度的65% */
        overflow: hidden;

        .video-cover {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s ease;
        }

        .video-duration {
          position: absolute;
          bottom: 8px;
          right: 8px;
          background-color: rgba(0, 0, 0, 0.7);
          color: white;
          padding: 2px 6px;
          border-radius: 4px;
          font-size: 0.8rem;
        }
      }

      .video-info {
        flex: 1;
        width: 100%;
        padding: 16px;
        /* 增加内边距 */

        .video-title {
          margin: 0 0 12px 0;
          /* 增加标题下方间距 */
          font-size: 1.05rem;
          /* 增大字体 */
          font-weight: 500;
          color: #ffffff;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .video-stats {
          display: flex;
          align-items: center;
          font-size: 0.85rem;
          color: #99a3a7;

          .stat {
            display: flex;
            align-items: center;
            margin-right: 12px;

            i {
              margin-right: 4px;
            }
          }

          .video-date {
            margin-left: auto;
            font-size: 0.8rem;
          }
        }
      }

      .remove-button {
        position: absolute;
        top: 8px;
        right: 8px;
        background-color: rgba(0, 0, 0, 0.5);
        border: none;
        border-radius: 50%;
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        opacity: 0;
        transition: all 0.2s ease;
        z-index: 2;
        color: #ffcc00;

        &:hover {
          background-color: rgba(0, 0, 0, 0.8);
          transform: scale(1.1);
        }

        .icon-remove {
          font-size: 1.2rem;
        }
      }
    }
  }
}

.empty-folder {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #99a3a7;

  .empty-icon {
    font-size: 2.5rem;
    margin-bottom: 16px;
  }

  .empty-text {
    font-size: 1rem;
  }
}

.create-folder-button {
  padding: 10px 24px;
  background: linear-gradient(45deg, #0096ff, #6c47ff);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 0.95rem;
  transition: all 0.2s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 150, 255, 0.3);
  }
}
</style>
